<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/10/25
// | DESC: 
// +----------------------------------------------------------------------

declare (strict_types=1);


namespace My\core\http;

class Response
{
    /**
     * @var \Swoole\Http\Response
     */
    protected $swooleResponse;
    protected $body;

    public function __construct($swooleResponse)
    {
        $this->swooleResponse = $swooleResponse;
        $this->setHeader('Content-Type', 'text/plain;charset=utf-8');
    }

    public static function init(\Swoole\Http\Response $response)
    {
        return new self($response);
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setBody($body): void
    {
        $this->body = $body;
    }

    public function setHeader($key, $val)
    {
        $this->swooleResponse->setHeader($key, $val);
    }

    public function status(int $status)
    {
        $this->swooleResponse->status($status);
    }

    public function redirect(string $uri, int $code = 301)
    {
        $this->status($code);
        $this->setHeader('Location',$uri);
    }

    public function end()
    {
        $res = $this->getBody();
        match (gettype($res)) {
            'array','object' => $this->handleJsonResponse($res),
            default => $this->handleRawResponse($res)
        };
        $this->swooleResponse->end();
    }

    private function handleJsonResponse($res): void
    {
        $this->setHeader('Content-Type', 'application/json;charset=utf-8');
        $this->swooleResponse->write(json_encode($res));
    }

    private function handleRawResponse($res): void
    {
        $this->swooleResponse->write($res);
    }
}